package com.scu.bank.model.base;

import com.scu.bank.util.ListUtils;
import com.scu.bank.util.StringGenerateUtil;
import com.scu.bank.util.WebUtil;

import java.util.Date;
import java.util.List;

public abstract class BaseServiceImpl<T extends BaseEntity,D extends BaseDao<T>> implements BaseService<T>{

    public abstract D getDao();

    @Override
    public int save(T entity){
        entity.setId(StringGenerateUtil.generatePrimaryKey());
        entity.setCreateTime(new Date());
        entity.setCreateUser(WebUtil.getCurrentUserId());
        entity.setDel(false);
        return getDao().insertSelective(entity);
    }

    @Override
    public int update(T entity){
        if (getById(entity.getId()) == null){
            return 0;
        }
        entity.setUpdateTime(new Date());
        entity.setUpdateUser(WebUtil.getCurrentUserId());
        return getDao().updateByPrimaryKey(entity);
    }

    @Override
    public int updateByPrimaryKeySelective(T entity){
        if (getById(entity.getId()) == null){
            return 0;
        }
        entity.setUpdateTime(new Date());
        entity.setUpdateUser(WebUtil.getCurrentUserId());
        return getDao().updateByPrimaryKeySelective(entity);
    }

    @Override
    public int deleteById(String id){
        T old = getById(id);
        if (old == null || !WebUtil.getCurrentUserId().equals(old.getCreateUser())){
            return 0;
        }
        return getDao().deleteByPrimaryKey(id);
    }

    @Override
    public int deleteByIds(List<String> ids){
        int count = 0;
        if (!ListUtils.isEmpty(ids)){
            for (String id : ids){
                count += deleteById(id);
            }
        }
        return count;
    }

    @Override
    public T getById(String id){
        return getDao().selectByPrimaryKey(id);
    }

    @Override
    public List<T> selectByExample(Object example){
        return getDao().selectByExample(example);
    }
}
